﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace LitS3
{
    /// <summary>
    /// Creates a new CloudFront distribution.
    /// </summary>
    public class CreateDistributionRequest : CloudFrontRequest<CreateDistributionResponse>
    {
        string request;

        public CreateDistributionRequest(CloudFrontService service, DistributionConfig config)
            : base(service, "POST", null, null)
        {
            request = config.ToXmlString();
            WebRequest.ContentType = "text/xml; charset=UTF-8";
            WebRequest.ContentLength = request.Length;
        }

        void WriteRequest(Stream stream)
        {
            var writer = new StreamWriter(stream, Encoding.ASCII);
            writer.Write(request);
            writer.Flush();
        }

        public override CreateDistributionResponse GetResponse()
        {
            AuthorizeIfNecessary();

            using (Stream stream = WebRequest.GetRequestStream())
                WriteRequest(stream);

            return base.GetResponse();
        }

        public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
        {
            throw new InvalidOperationException("BeginGetResponse() is not supported for this class yet.");
        }
    }

    /// <summary>
    /// Represents a CloudFront response for a created bucket.
    /// </summary>
    public class CreateDistributionResponse : CloudFrontResponse
    {
        public Distribution Distribution { get; private set; }

        protected override void ProcessResponse()
        {
            Distribution = new Distribution(Reader);
        }
    }
}
